    using Microsoft.AspNetCore.Mvc;
    using RAG.Application.Services;
    using Microsoft.AspNetCore.Authorization;
    using System.Security.Claims;

    namespace RAG.Api.Controllers;

    [ApiController]
    [Route("api/[controller]")]
    [Authorize] // 添加认证要求
    public class DocumentsController : ControllerBase
    {
        private readonly IDocumentApplicationService _documentService;
        private readonly ILogger<DocumentsController> _logger;

        public DocumentsController(IDocumentApplicationService documentService, ILogger<DocumentsController> logger)
        {
            _documentService = documentService;
            _logger = logger;
        }

        /// <summary>
        /// 批量上传文档
        /// </summary>
        [HttpPost("upload")]
        public async Task<IActionResult> UploadDocuments([FromForm] IFormFileCollection files, [FromForm] string? description, [FromForm] string? tags, [FromForm] string accessLevel = "Internal")
        {
            try
            {
                if (files == null || !files.Any())
                {
                    return BadRequest(new { error = "请选择要上传的文件" });
                }

                            // 从JWT token中获取用户ID
            var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
            _logger.LogInformation("JWT token中的用户ID: {UserId}", userIdClaim?.Value);
            
            if (userIdClaim == null || !Guid.TryParse(userIdClaim.Value, out var userId))
            {
                return Unauthorized(new { error = "无法获取用户信息" });
            }
            
            _logger.LogInformation("解析后的userId: {UserId}, 类型: {Type}", userId, userId.GetType().Name);

                // 转换为FileInfo
                var fileInfos = new List<RAG.Domain.Services.FileInfo>();
                foreach (var file in files)
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        await file.CopyToAsync(memoryStream);
                        fileInfos.Add(new RAG.Domain.Services.FileInfo
                        {
                            FileName = file.FileName,
                            ContentType = file.ContentType,
                            Length = file.Length,
                            Content = memoryStream.ToArray()
                        });
                    }
                }

                var request = new UploadFilesRequest
                {
                    Files = fileInfos,
                    Description = description,
                    Tags = tags,
                    AccessLevel = accessLevel
                };

                var result = await _documentService.UploadFilesAsync(request, userId);

                _logger.LogInformation("批量上传完成: 成功 {SuccessCount} 个, 失败 {FailedCount} 个", 
                    result.SuccessCount, result.FailedCount);

                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "文档上传失败");
                return BadRequest(new { error = ex.Message });
            }
        }

        /// <summary>
        /// 获取文档列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetDocuments(
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 20,
            [FromQuery] string? keyword = null,
            [FromQuery] string? accessLevel = null)
        {
            try
            {
                var result = await _documentService.GetDocumentsAsync(page, pageSize, keyword, accessLevel);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取文档列表失败");
                return BadRequest(new { error = ex.Message });
            }
        }

        /// <summary>
        /// 获取单个文档
        /// </summary>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetDocument(Guid id)
        {
            try
            {
                var document = await _documentService.GetDocumentByIdAsync(id);
                if (document == null)
                {
                    return NotFound(new { error = "文档不存在" });
                }

                return Ok(document);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取文档失败: {Id}", id);
                return BadRequest(new { error = ex.Message });
            }
        }

        /// <summary>
        /// 更新文档信息
        /// </summary>
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateDocument(Guid id, [FromBody] DocumentUpdateRequest updateRequest)
        {
            try
            {
                var document = await _documentService.UpdateDocumentAsync(id, updateRequest);
                if (document == null)
                {
                    return NotFound(new { error = "文档不存在" });
                }

                return Ok(document);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新文档失败: {Id}", id);
                return BadRequest(new { error = ex.Message });
            }
        }

        /// <summary>
        /// 删除单个文档
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteDocument(Guid id)
        {
            try
            {
                var result = await _documentService.DeleteDocumentAsync(id);
                if (!result)
                {
                    return NotFound(new { error = "文档不存在" });
                }

                return Ok(new { message = "文档删除成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除文档失败: {Id}", id);
                return BadRequest(new { error = ex.Message });
            }
        }

        /// <summary>
        /// 批量删除文档
        /// </summary>
        [HttpDelete("batch")]
        public async Task<IActionResult> DeleteDocuments([FromBody] List<Guid> ids)
        {
            try
            {
                if (ids == null || !ids.Any())
                {
                    return BadRequest(new { error = "请选择要删除的文档" });
                }

                var result = await _documentService.DeleteDocumentsAsync(ids);
                if (!result)
                {
                    return NotFound(new { error = "没有找到要删除的文档" });
                }

                return Ok(new { message = $"成功删除 {ids.Count} 个文档" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除文档失败");
                return BadRequest(new { error = ex.Message });
            }
        }

        /// <summary>
        /// 获取文档统计信息
        /// </summary>
        [HttpGet("statistics")]
        public async Task<IActionResult> GetDocumentStatistics()
        {
            try
            {
                var statistics = await _documentService.GetDocumentStatisticsAsync();
                return Ok(statistics);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取文档统计信息失败");
                return BadRequest(new { error = ex.Message });
            }
        }
    } 